/*
Simple Forum Auto Poster.
Copyright (C) 2011 Gianni Van Hoecke.

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/
package persistence.net;

import domain.DomainController;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;

/**
 *
 * @author Gianni Van Hoecke <gianni.vh@gmail.com>
 */
public class URLChecker
{
    /**
     * Tries to verify the given URL.
     * Internet connection must be present!
     * @param value The URL to verify.
     * @param showErrors True to show the errors, if any.
     * @return True if the URL is valid and accessible, false otherwise.
     */
    public static boolean check(String value, boolean showErrors)
    {
        try
        {
            URL url = new URL(value);
            URLConnection conn = url.openConnection();
            conn.connect();
            //All OK!
            return true;
        }
        catch (MalformedURLException e)
        {
            if(showErrors)
            {
                String err = "The URL is not in a valid form.";
                DomainController.getInstance().getLogger().log(Level.WARNING, err);
                DomainController.getInstance().fireMessage(err, "Error");
            }
        }
        catch (IOException e)
        {
            if(showErrors)
            {
                String err = "The connection couldn't be established. Check your internet connection and whether the URL is accessible or not.";
                DomainController.getInstance().getLogger().log(Level.WARNING, err);
                DomainController.getInstance().fireMessage(err, "Error");
            }
        }
        catch (Exception e)
        {
            if(showErrors)
            {
                String err = "The URL is not in a valid form.";
                DomainController.getInstance().getLogger().log(Level.WARNING, err);
                DomainController.getInstance().fireMessage(err, "Error");
            }
        }
        
        return false;
    }
}